//
//  TestStatement.m
//  ObjectivePQ
//
//  Created by Ian and Sadie Michell on 31/01/2009.
//  Copyright 2009 Ian Michell. All rights reserved.
//

#import "TestStatement.h"

@implementation TestStatement

- (void) setUp
{
	// Create connection for test
	NSString* connStr = @"host='localhost' port='5432' dbname='template1' user='postgres' password=''";
	self->conn = [[PQConnection alloc] initWithConnectionString: connStr];
	[self->conn connect];
	STAssertTrue([self->conn isConnected], @"Connection is not active");
}

- (void) tearDown
{
	// Close the connection after the test.
	[self->conn close];
	STAssertFalse([self->conn isConnected], @"The connection is still alive!");
}

/* Tests a simple select statement using execute */
- (void) testExecuteSelectStatement
{
	id <DBStatement> stmt = [self->conn createStatementWithQuery: @"SELECT datname FROM pg_catalog.pg_database d"];
	@try
	{
		bool result = [stmt execute];
		// Assert that the statement executed correctly (non-fatal won't throw an exception */
		STAssertTrue(result, [stmt getErrorMessage]);
	}
	@catch (NSException* e) 
	{
		STFail([e reason]);
	}
}

- (void) testexecuteSelectStatementWithResultSet
{
	// Do the same statement as the last test, but this time check that we get a result set and that it contains
	// the template1 table
	id <DBStatement> stmt = [self->conn createStatementWithQuery: @"SELECT d.datname FROM pg_catalog.pg_database d WHERE d.datname = 'template1'"];
	@try
	{
		bool result = [stmt execute];
		// Assert that the statement executed correctly (non-fatal won't throw an exception, we just return false)
		STAssertTrue(result, [stmt getErrorMessage]);
		id <DBResultSet> rs = [stmt getResultSet];
		STAssertTrue([rs rowCount] > 0, @"No results found in query");
	}
	@catch (NSException* e) 
	{
		STFail([e reason]);
	}
}
@end
